package com.example.news;

import androidx.appcompat.app.AppCompatActivity;

import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.EditText;
import android.widget.Toast;

import com.example.news.dao.UserDao;
import com.example.news.entity.User;
import com.orm.util.ManifestHelper;

public class RegisterNewUserActivity extends AppCompatActivity implements View.OnClickListener {

    private EditText et_user_name;
    private EditText et_user_pwd;
    private EditText et_user_pwd2;
    private EditText et_user_nick;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_register_new_user);

        et_user_name = findViewById(R.id.et_user_name);
        et_user_pwd = findViewById(R.id.et_user_pwd);
        et_user_pwd2 = findViewById(R.id.et_user_pwd2);
        et_user_nick = findViewById(R.id.et_user_nick);
        findViewById(R.id.btn_reg).setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {
        int id = v.getId();
        if (id == R.id.btn_reg) {
            String databaseName = ManifestHelper.getDatabaseName(this);
            String userName = et_user_name.getText().toString();
            String userPwd = et_user_pwd.getText().toString();
            String userPwd2 = et_user_pwd2.getText().toString();
            if (TextUtils.isEmpty(userName)) {
                Toast.makeText(this, "用户名不能为空", Toast.LENGTH_SHORT).show();
                return;
            }
            if (TextUtils.isEmpty(userPwd) || TextUtils.isEmpty(userPwd2)) {
                Toast.makeText(this, "密码和确认密码能为空", Toast.LENGTH_SHORT).show();
                return;
            }
            if (!userPwd.equals(userPwd2)) {
                Toast.makeText(this, "密码和确认密码不一致，请确认", Toast.LENGTH_SHORT).show();
                return;
            }
            // 手机号已经存在的
            long cnt = UserDao.queryPhone(userName);
            if (cnt > 0) {
                Toast.makeText(this, "未知原因失败，请联系管理员", Toast.LENGTH_SHORT).show();
                return;
            }
            User user = new User(userName, userPwd);
            String nickName = et_user_nick.getText().toString();
            if (!TextUtils.isEmpty(nickName)) {
                user.setNickName(nickName);
            }
            long save = User.save(user);
            if (save > 1) {
                Toast.makeText(this, "注册成功，请登陆", Toast.LENGTH_SHORT).show();
//                Intent intent = new Intent(this, LoginActivity.class);
//                startActivity(intent);
                finish();
            } else {
                Toast.makeText(this, "注册失败，请联系管理员", Toast.LENGTH_SHORT).show();
            }
        }
    }
}